﻿using System;
using System.Globalization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.ApplicationPages;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.ApplicationPages.WebControls;

namespace Voodoo.SharePoint.ReadUnreadMarks
{
    public partial class ListItemReadUnreadSiteColumnConfigureSettings : Microsoft.SharePoint.ApplicationPages.OperationsPage
    {
        protected Button btnCancel;
        protected Button btnApply;
        protected CheckBox chkDocumentTracking;
        protected CheckBox chkDirectWrites;
        protected CheckBox chkOfficeDocumentTracking;
        protected DropDownList cboThreadCount;

      
        private static SPWebConfigModification _HTTPModuleModification = new SPWebConfigModification()
        {
            Owner = UtilityMethods.WEB_CONFIG_OWNER,
            Name = "add[@name='" + UtilityMethods.WEB_CONFIG_OWNER + "']",
            Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode,
            Path = "configuration/system.webServer/modules",
            Sequence = 0,
            Value = "<add name='" + UtilityMethods.WEB_CONFIG_OWNER + "' type='Voodoo.SharePoint.ReadUnreadMarks.ReadUnreadHTTPModule," +
                      System.Reflection.Assembly.GetExecutingAssembly().FullName + "' />"

        };

        private static SPWebConfigModification _AppSettingsModification = new SPWebConfigModification()
        {
            Owner = UtilityMethods.WEB_CONFIG_OWNER,
            Name = "add[@key='" + UtilityMethods.THREAD_COUNT_APP_SETTING_NAME + "']",
            Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode,
            Path = "configuration/appSettings",
            Sequence = 0,
            Value = ""

        };

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SPFarm.Local.CurrentUserIsAdministrator())
            {
                btnCancel.Click += new EventHandler(btnCancel_Click);
                btnApply.Click += new EventHandler(btnApply_Click);
                chkDocumentTracking.CheckedChanged += new EventHandler(chkDocumentTracking_CheckedChanged);
                if (!Page.IsPostBack)
                {
                    ReadUnreadFarmSettings globalSettings = null;
                    try
                    {
                        globalSettings = (ReadUnreadFarmSettings)SPFarm.Local.GetObject(ReadUnreadFarmSettings.SETTINGS_ID);
                    }
                    catch
                    {
                        globalSettings = null;
                    }
                    if (null == globalSettings)
                    {
                        chkDirectWrites.Checked = false;
                        chkDocumentTracking.Checked = false;
                        chkOfficeDocumentTracking.Checked = false;
                        cboThreadCount.SelectedIndex = 0;
                    }
                    else
                    {
                        chkDirectWrites.Checked = globalSettings.WriteDirect;
                        chkDocumentTracking.Checked = globalSettings.TrackDocuments;
                        chkOfficeDocumentTracking.Checked = globalSettings.TrackOfficeDocuments;
                        if (globalSettings.DocumentTrackerBackgroundThreadCount > 1)
                        {
                            cboThreadCount.SelectedIndex = globalSettings.DocumentTrackerBackgroundThreadCount -1;
                        }
                        else
                        {
                            cboThreadCount.SelectedIndex = 0;
                        }
                    }
                }
            }
            else
            {
                btnApply.Enabled = false;
                chkDirectWrites.Enabled = false;
                chkDocumentTracking.Enabled = false;
                cboThreadCount.Enabled = false;
                chkOfficeDocumentTracking.Enabled = false;
                lblErrorMessage.Text = "You must be a farm administrator to manage global Read Unread configuration";
            }

        }

        void chkDocumentTracking_CheckedChanged(object sender, EventArgs e)
        {
            if (chkDocumentTracking.Checked)
            {
                chkDirectWrites.Checked = true;
            }
        }


        protected void btnApply_Click(object sender, EventArgs e)
        {
            ReadUnreadFarmSettings globalSettings = null;
            try
            {

                globalSettings = (ReadUnreadFarmSettings)SPFarm.Local.GetObject(ReadUnreadFarmSettings.SETTINGS_ID);

                if (null == globalSettings) globalSettings = new ReadUnreadFarmSettings("ReadUnreadGlobalSettings", SPFarm.Local, ReadUnreadFarmSettings.SETTINGS_ID);
                globalSettings.WriteDirect = chkDirectWrites.Checked;
                if (globalSettings.WriteDirect)
                {
                    globalSettings.TrackDocuments = chkDocumentTracking.Checked;
                    if (globalSettings.TrackDocuments)
                    {
                        globalSettings.DocumentTrackerBackgroundThreadCount = cboThreadCount.SelectedIndex;
                        globalSettings.TrackOfficeDocuments = chkOfficeDocumentTracking.Checked;
                    }
                    else
                    {
                        globalSettings.TrackOfficeDocuments = false;
                        globalSettings.DocumentTrackerBackgroundThreadCount = 0;
                    }
                }
                else
                {
                    globalSettings.TrackDocuments = false;
                    globalSettings.TrackOfficeDocuments = false;
                    globalSettings.DocumentTrackerBackgroundThreadCount = 0;
                }

                globalSettings.Update(false);
                if (globalSettings.TrackDocuments)
                {
                    RegisterHTTPHandler(globalSettings.DocumentTrackerBackgroundThreadCount);
                }
                else
                {
                    UnRegisterHTTPHandler();
                }

                chkDirectWrites.Checked = globalSettings.WriteDirect;
                chkDocumentTracking.Checked = globalSettings.TrackDocuments;
                chkOfficeDocumentTracking.Checked = globalSettings.TrackOfficeDocuments;
                if (globalSettings.DocumentTrackerBackgroundThreadCount > 1)
                {
                    cboThreadCount.SelectedIndex = globalSettings.DocumentTrackerBackgroundThreadCount - 1;
                }
                else
                {
                    cboThreadCount.SelectedIndex = 0;
                }
                lblMessage.Text = "Settings updated ";
            }
            catch (Exception saveError)
            {
                globalSettings.Delete();
               
                btnApply.Enabled = false;
                chkDirectWrites.Enabled = false;
                chkDocumentTracking.Enabled = false;
                cboThreadCount.Enabled = false;
                chkOfficeDocumentTracking.Enabled = false;
                lblErrorMessage.Text = saveError.Message;
            }

        }


        protected void btnCancel_Click(object sender, EventArgs e)
        {
            SPScenarioContext context = null;
            try
            {
                context = SPScenarioContext.GetContext(this, CultureInfo.CurrentCulture);
            }
            catch (SPException)
            {
            }
            if (context != null)
            {
                context.TransitionToCancelPage(true);
            }
            else
            {
                SPUtility.Redirect("/_admin/VoodooConfiguration.aspx", SPRedirectFlags.Default, this.Context);
            }
        }

        internal static void UnRegisterHTTPHandler()
        {
            SPWebService webService = SPWebService.ContentService;
            System.Collections.ObjectModel.Collection<SPWebConfigModification> modificationCollection = webService.WebConfigModifications;
            int modificationCount = modificationCollection.Count;
            //walk backwards after preserving count because we will modify the
            //collection during this loop
            for (int countIndex = modificationCount - 1; countIndex > -1; countIndex--)
            {
                if ((modificationCollection[countIndex].Owner == UtilityMethods.WEB_CONFIG_OWNER))
                {
                    SPWebConfigModification foundModification = modificationCollection[countIndex];
                    modificationCollection.Remove(foundModification);
                    webService.Update();
                    webService.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                }
            }
            webService.Update();
            webService.ApplyWebConfigModifications();

        }

        void RegisterHTTPHandler(int appSettingsThreadCount)
        {

            SPWebService webService = SPWebService.ContentService;
            SPWebConfigModification configMod = new SPWebConfigModification("appSettings", "configuration");
            configMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureSection;
            webService.WebConfigModifications.Add(configMod);
            webService.Update();
            webService.ApplyWebConfigModifications();

            webService.WebConfigModifications.Add(_HTTPModuleModification);
            webService.Update();
            webService.ApplyWebConfigModifications();

            _AppSettingsModification.Value = "<add key='" + UtilityMethods.THREAD_COUNT_APP_SETTING_NAME + "' value='" + appSettingsThreadCount.ToString() + "' />";
            webService.WebConfigModifications.Add(_AppSettingsModification);
            webService.Update();
            webService.ApplyWebConfigModifications();

        }

    }
}
